package ch.didierviret.memgest.server.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import ch.didierviret.memgest.shared.entities.Membership;

import com.google.appengine.api.datastore.Key;

public class MembershipDAO {
	private EntityManager em;

	public MembershipDAO() {
		em = EMF.get().createEntityManager();
	}

	public void finalize() {
		em.close();
	}

	public void delete(Membership e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		e = em.merge(e);
		em.remove(e);
		tx.commit();
	}

	// TODO Delete all : Remove after testing ?
	public void deleteAll() {
		em.createQuery("DELETE FROM Membership").executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<Membership> findAll() {
		List<Membership> memberships = em.createQuery(
				"SELECT e FROM Membership e").getResultList();
		return memberships;
	}

	public Membership findByKey(Key key) {
		return em.find(Membership.class, key);
	}

	public Membership insert(Membership e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		em.persist(e);
		tx.commit();
		return e;
	}

	public Membership update(Membership e) {
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		e = em.merge(e);
		tx.commit();
		return e;
	}
}
